package com.lwx.sys.controller;

import com.lwx.sys.utils.DataGridView;
import com.lwx.sys.utils.FileUpLoadAndDownUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/file")
public class FileController {

    /**
     * 临时文件的保存路径 -> D:/upload
     */
    @Value("${upload.upload-root-path}")
    private String uploadRootPath;

    /**
     * 上传文件
     * @param mf //mf要和前台的mf保持一致
     * @return
     */
    @PostMapping("/uploadFile")
    public DataGridView uploadFile(MultipartFile mf){
        //获得文件名
        String oldName = mf.getOriginalFilename();
        String dirName = FileUpLoadAndDownUtil.getDirNameByCurrentDate();
        File file = new File(uploadRootPath, dirName);
        if (file.exists() && StringUtils.isNotEmpty(oldName)){
            //新生成的文件名
            String fileNameUse = FileUpLoadAndDownUtil.getNewFileNameUseUUID(oldName);
            //新文件
            File newFile = new File(file, fileNameUse);
            try {
                //上传文件到uploadRootPath
                mf.transferTo(newFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Map<String,Object> src=new HashMap<>();
            src.put("src","/"+dirName+"/"+fileNameUse);
            return new DataGridView(src);
        }
       return new DataGridView();
    }

    /**
     * 展示图片
     * @param filePath 文件路径
     * @return
     */
    @GetMapping("/showImage")
    public ResponseEntity<Object> showImage(String filePath){
        return  FileUpLoadAndDownUtil.showImage(uploadRootPath,filePath);
    }

}
